package com.dayou.interceptor;


import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dayou.common.exception.BusinessException;
import com.dayou.common.utils.IpUtils;
import com.dayou.common.utils.LogUtil;
import com.dayou.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;

@Component
public class ServiceInterceptor implements HandlerInterceptor {
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Value("${server-config.allow-origin}")
    private String allowOrigin;


    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private LogUtil logUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String ip = IpUtils.getIpAddr(request);
        String method = request.getMethod();
        if(StringUtils.isEmpty(method)){
            throw new BusinessException("请求方法异常");
        }else if("OPTIONS".equals(method)){
            return true;
        }
        logUtil.debug(String.format("%s发起请求", ip));
        HttpSession session = request.getSession();
        if(null == session.getAttribute("login_user")){
            throw new BusinessException("未获取到登录信息，请重新登录");
        }
        String origin = request.getHeader("Origin");
        if(!allowOrigin.equals(origin)){
            return true;
        }
        // 获取redis中的Tokens
        List<Object> tokens = redisUtils.lRange("Tokens", 0, redisUtils.lSize("Tokens") - 1);
        if(tokens.size() == 0){
            logUtil.warn("Tokens的缓存数据长度为0，跳过token验证");
            return true;
        }
        String headerToken = request.getHeader("token");
        if (StringUtils.isEmpty(headerToken)) {
            throw new BusinessException("token验证失败：未获取到token");
        }
        //将请求头中的token以,分割为数组
        String[] headerTokens = headerToken.split(",");
        //判断请求头中的token是否含有与redis中相同的任意一项，若无，则拦截
        boolean flag = true;
        out:
        for (String hToken : headerTokens) {
            for (Object token : tokens) {
                if (token.equals(hToken)) {
                    flag = false;
                    break out;
                }
            }
        }
        if (flag) {
            throw new BusinessException("token验证失败：token不正确");
        }
        return true;
    }

    @PostConstruct
    private void afterInit() {
        if (!redisUtils.exists("Tokens")) {
            logUtil.warn("未获取到Tokens的缓存数据");
        }
    }
}
